package cn.edu.neu.vmmigeval.cloud.policy;

import cn.edu.neu.vmmigeval.cloud.entity.Host;
import cn.edu.neu.vmmigeval.cloud.entity.Vm;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public abstract class VmSelectionPolicy {
	
	private MigratedHostPolicy migratedHostPolicy;
	
	public VmSelectionPolicy(){
		
	}
	
	public VmSelectionPolicy(MigratedHostPolicy migratedHostPolicy){
		this.migratedHostPolicy = migratedHostPolicy;
	}
	
	public List<Vm> getMigratedVmsfromHost(Host host){
		List<Vm> vmsToMigrate = new LinkedList<Vm>();
		while (true) {
			Vm vm = getVmToMigrate(host);
			if (vm == null) {
				break;
			}
			vmsToMigrate.add(vm);
			/*if (!this.getMigratedHostPolicy().isHostOverUtilized(host)) {
				break;
			}*/
			if(!isHostOverUtilizedWithoutVms(host,vmsToMigrate)){
				break;
			}
		}
		return vmsToMigrate;
		
	}

	public abstract Vm getVmToMigrate(Host host);

	public List<Vm> getMigratableVms(Host host) {
		List<Vm> migratableVms = new ArrayList<Vm>();
		for (Vm vm : host.getVmList()) {
			if (!vm.isInMigration()) {
				migratableVms.add(vm);
			}
		}
		return migratableVms;
	}
	
	public MigratedHostPolicy getMigratedHostPolicy() {
		return migratedHostPolicy;
	}

	public void setMigratedHostPolicy(MigratedHostPolicy migratedHostPolicy) {
		this.migratedHostPolicy = migratedHostPolicy;
	}
	
	public boolean isHostOverUtilizedWithoutVms(Host host,List<Vm> vms){
		
		int currentAllocationCpu = 0 ;
		int totalAllocationRam = 0 ;
		
		for (Vm vmOfHost : vms) {
			currentAllocationCpu+=vmOfHost.getCurrentCpu();
			totalAllocationRam+=vmOfHost.getTotalRam();
		}
		if((host.getTotalCpu()-totalAllocationRam)<=0.0){
			return false;
		}
		if((double)(host.getCurrentCpu()-currentAllocationCpu)/(host.getTotalCpu()-totalAllocationRam)>0.9){
			return true;
		}else{
			return false;
		}
	}
	
		
}
